﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Telerik.Web.UI;
using Dimok.Web.UI;
using Data.LINQ;

namespace Dimok.Web.UI {
	/// <summary>
	/// Summary description for ServerControl1
	/// </summary>
	public class TableControlAjax : UserControl,IScriptControl {
		#region Properties
		public Control Container;
		RadGridExtender radGridExtender;
		RadGrid radGrid;
		ScriptManager sm;
		public List<string> ScriptsToPreLoad = new List<string>();
		public string CssClass { get; set; }
		public string GridCssClass { get; set; }
		public string GridStyle { get; set; }
		public bool? FloatLeft { get; set; }
		public string Skin { get; set; }
		public Type WSEntityType { get; set; }
		public string ProfileID { get; set; }

		public string ClientType { get; set; }
		public string WSMethodName { get; set; }
		public string WSMethodName_Delete { get; set; }
		public string DocksID { get; set; }
		public Control RowContextMenu { get; set; }
		#endregion

		#region OnLoad
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			
			Container = FindControl("Container");
			#region Create Table Extender Container if doesn't exist
			if (Container == null) {
				Container = new Label() { ID = "Container" };
				Controls.Add(Container);
			}
			#endregion

			radGridExtender = this.Child<RadGridExtender>();
			if (radGridExtender == null) {
				radGridExtender = new RadGridExtender();
				radGridExtender.ID = "rge";
				this.Controls.Add(radGridExtender);
			}
			radGrid = this.Child<Telerik.Web.UI.RadGrid>();
			var lds = this.Child<LinqDataSource>();
			if (radGrid == null)
				radGrid = new Telerik.Web.UI.RadGrid();
			if (radGrid.ID + "" == "") radGrid.ID = "rgc";
			
			//if (lds == null) {
			//  lds = new LinqDataSource();
			//  this.Controls.Add(lds);
			//  //lds.ContextTypeName = typeof(MotoBank).FullName;
			//  //lds.TableName = MotoBank.MetaModel.Tables.Single(t => t.EntityType == WSEntityType).Name;
			//  //lds.Where = MotoBank.MetaModel.GetDefaultFilter(WSEntityType);
			//  lds.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(lds_Selecting);
			//}
			if (radGrid.Parent == null)
				this.Controls.Add(radGrid);
			if (WSEntityType != null) radGridExtender.WSEntityType = WSEntityType;
			if (ProfileID + "" != "") radGridExtender.ProfileID = ProfileID;
            radGrid.DataBinding += new EventHandler(radGrid_DataBinding);
		}

        void radGrid_DataBinding(object sender, EventArgs e)
        {
            var lds = radGrid.DataSource as LinqDataSource;
            if (lds != null && lds.TableName == "v_Uploads")
                lds.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(lds_Selecting);
        }

		void lds_Selecting(object sender, LinqDataSourceSelectEventArgs e) {
			e.Result = new MotoBank().GetTable(WSEntityType).Where(MotoBank.MetaModel.GetDefaultFilter(WSEntityType));
		}
		#endregion

		#region OnPre(Render)
		protected override void OnPreRender(EventArgs e) {
			if (!this.DesignMode) {
				sm = ScriptManager.GetCurrent(Page);
				if (sm == null) throw new HttpException("A ScriptManager control must exist on the current page.");
				sm.RegisterScriptControl(this);
			}
			base.OnPreRender(e);
			Container.AppendStyle(this.Attributes);
			//Container.AppendStyle("float:" + (FloatLeft == null || FloatLeft == true ? "left" : "none"));
			Container.AppendCssClass(CssClass);
			if (Skin + "" != "") {
				Container.AppendCssClass(Skin);
				radGridExtender.Skin = Skin;
			}
			if (GridCssClass + "" != "") radGridExtender.CssClass += " " + GridCssClass;
			if (GridStyle + "" != "") radGridExtender.Style += ";" + GridStyle;
			if (DocksID + "" != "") radGridExtender.DocksID = DocksID;
			if (RowContextMenu != null) radGridExtender.RowContextMenuID = RowContextMenu.ClientID;
			radGridExtender.TargetControlID = radGrid.ID;
			if (WSMethodName + "" != "") radGridExtender.WSMethodName = WSMethodName;
			if (WSMethodName_Delete + "" != "") radGridExtender.WSMethodName_Delete = WSMethodName_Delete;
		}
		protected override void Render(HtmlTextWriter writer) {
			if (!this.DesignMode) sm.RegisterScriptDescriptors(this);
			base.Render(writer);
		}
		#endregion

		#region ScriptControl
		protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors() {
			if (Page.AppRelativeVirtualPath != null) {
				ScriptControlDescriptor descriptor =
					new ScriptControlDescriptor(ClientType + "" != "" ? ClientType : "Dimok.Table", Container.ClientID);
				descriptor.AddProperty("id", Container.ClientID);
				descriptor.AddComponentProperty("RGE", radGridExtender.ClientID);
				if (RowContextMenu != null && RowContextMenu.Child("txtAttachName") != null) {
					descriptor.AddElementProperty("txtAttachName", RowContextMenu.Child("txtAttachName").ClientID);
					descriptor.AddElementProperty("attachButton", RowContextMenu.Child("btnAttachFile").ClientID);
					descriptor.AddElementProperty("fileAttach", RowContextMenu.Child("fileAttach").ClientID);
				}
				yield return descriptor;
			}
		}
		protected virtual IEnumerable<ScriptReference> GetScriptReferences() {
			if (Page.AppRelativeVirtualPath != null) {
				yield return new ScriptReference("/JS/UI/Dimok.Table.js");
				foreach (var path in ScriptsToPreLoad)
					yield return new ScriptReference(path);
				yield return new ScriptReference(System.IO.Path.ChangeExtension(this.AppRelativeVirtualPath, "js"));
			}

		} 
		#endregion

		#region IScriptControl Members
		IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors() {
			return GetScriptDescriptors();
		}
		IEnumerable<ScriptReference> IScriptControl.GetScriptReferences() {
			return GetScriptReferences();
		}
		#endregion
	}
}